package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.mapper.AdSensitiveMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.util.GreenImageScan;
import com.usian.common.aliyun.util.GreenTextScan;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsVo;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private AdChannelService adChannelService;

    @Autowired
    private AdSensitiveMapper adSensitiveMapper;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        if (id==null){
            return;
        }
        WmNews wmNews = wemediaFeign.findByNewsId(id);
        if (wmNews==null || wmNews.getStatus() == 0){
            return;
        }

        if (wmNews.getStatus()==4){
            this.saveArticle(wmNews);
        }
        if (wmNews.getStatus()==8 && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            this.saveArticle(wmNews);
        }
        if (wmNews.getStatus()==1){
            Map<String, Object> map = this.handleTextAndImages(wmNews);
            String textStr =(String) map.get("content");
            boolean textScan = this.handleTextScan(textStr, wmNews);
            if (!textScan){
                return;
            }
            List<String> imageList = (List<String>) map.get("images");
            boolean imagesScan = this.handleImagesScan(imageList, wmNews);
            if (!imagesScan){
                return;
            }

            boolean handleSensitive = this.handleSensitive(textStr, wmNews);
            if (!handleSensitive){
                return;
            }

        }

        if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
            this.updateWmNewStatus(wmNews,(short)8,"审核通过，待发布");
        }else {
            this.updateWmNewStatus(wmNews,(short)9,"审核通过，已发布");
        }

        this.saveArticle(wmNews);

    }

    private boolean handleSensitive(String content,WmNews wmNews){
        boolean flag = false;
        List<String> allSensitive = adSensitiveMapper.findAllSensitive();
        SensitiveWordUtil.initMap(allSensitive);
        Map<String, Integer> words = SensitiveWordUtil.matchWords(content);
        if (words.size()==0){
            flag = true;
        }else {
            this.updateWmNewStatus(wmNews,(short)2,"内容中包含敏感词");
        }
        return flag;
    }

    private Map<String,Object> handleTextAndImages(WmNews wmNews){
        String content = wmNews.getContent();
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList<String> imageList = new ArrayList<>();
        List<Map> list = JSON.parseArray(content, Map.class);
        for (Map map : list) {
            if (map.get("type").equals("text")){
                stringBuilder.append(map.get("value"));
            }
            if (map.get("type").equals("image")){
                imageList.add(map.get("value").toString());
            }
        }
        if (wmNews.getImages()!=null && wmNews.getType()>0){
            String[] strings = wmNews.getImages().split(",");
            imageList.addAll(Arrays.asList(strings));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", stringBuilder.toString());
        resultMap.put("images", imageList);
        return resultMap;
    }

    private boolean handleImagesScan(List<String> images, WmNews wmNews){
        if (images == null) {
            return true;
        }

        boolean flag = false;

        try {
            List<byte[]> imageList = new ArrayList<>();
            for (String image : images) {
                String replace = image.replace(fileServerUrl, "");
                String groupName = replace.substring(0, replace.indexOf("/"));
                String groupPath = replace.substring(replace.indexOf("/")+1);
                byte[] bytes = fastDFSClientUtil.download(groupName, groupPath);
                imageList.add(bytes);
            }
            Map map = greenImageScan.imageScan(imageList);
            if (!map.get("suggestion").equals("pass")){
                if (map.get("suggestion").equals("block")){
                    this.updateWmNewStatus(wmNews,(short)2,"图片审核不通过");
                }
                if (map.get("suggestion").equals("review")){
                    this.updateWmNewStatus(wmNews,(short)3,"图片审核不确定，建议人工审核");
                }
            }else {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    private boolean handleTextScan(String content, WmNews wmNews){
        boolean flag = false;
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (!map.get("suggestion").equals("pass")){
                if (map.get("suggestion").equals("block")){
                    this.updateWmNewStatus(wmNews,(short)2,"文本审核不通过");
                }
                if (map.get("suggestion").equals("review")){
                    this.updateWmNewStatus(wmNews,(short)3,"文本审核不确定，建议人工审核");
                }
            }else {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    private void updateWmNewStatus(WmNews wmNews,Short status,String msg){
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaFeign.updateNewStatus(wmNews);
    }


    private void saveArticle(WmNews wmNews){
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());

        Integer userId = wmNews.getUserId();
        ApAuthor apAuthor = articleFeign.findByWmUserId(userId);
        if (apAuthor!=null){
            apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
            apArticle.setAuthorName(apAuthor.getName());
        }

        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelService.getById(channelId);
        if (adChannel!=null){
            apArticle.setChannelId(channelId);
            apArticle.setChannelName(adChannel.getName());
        }
        ApArticle apArticle1 = articleFeign.saveApArticle(apArticle);


        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle1.getId());
        apArticleContent.setContent(wmNews.getContent());
        ApArticleContent apArticleContent1 = articleFeign.saveApArticleContent(apArticleContent);


        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle1.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);

        ApArticleConfig apArticleConfig1 = articleFeign.saveApArticleConfig(apArticleConfig);
    }

    @Override
    public ResponseResult findNews(NewsAuthDto dto) {
        ResponseResult list = wemediaFeign.findList(dto);
        list.setHost(fileServerUrl);
        return list;
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {

        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileServerUrl);

        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {

        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = wemediaFeign.findWmNewsVo(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.审核没有通过
        if(type.equals(0)){
            updateWmNewStatus(wmNews,(short)2,dto.getMsg());
        }else if(type.equals(1)){
            //4.人工审核通过
            updateWmNewStatus(wmNews,(short)4,"人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
